package server;

import java.lang.Thread.State;

import util.Utilities;
import dao.Linker;

public class Reloader implements Runnable
{
	private Server server;
	private String port;
	private Thread serverThread;
	private String lastTimeCheck = "";
	
	public Reloader(String port) throws Exception
	{
		this.port = port;
		server = new Server(port);
		serverThread = new Thread(server);
		serverThread.start();
		lastTimeCheck = Utilities.getDateTime("yyyy-MM-dd");
		Linker.init();
	}
	
	public synchronized void run()
	{
		while(true)
		{
			try
			{
				wait(60*60*1000);
			} 
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			if( !lastTimeCheck.equals(Utilities.getDateTime("yyyy-MM-dd")) )
			{
				System.out.println("Making update - " + Utilities.getDateTime("yyyy-MM-dd HH:mm:ss"));
				
				if( serverThread.getState().equals(State.TERMINATED) )
				{
					System.out.println("Server state - " + serverThread.getState());
					server.closeEndpoints();
					
					try
					{
						server = new Server(port);
						serverThread = new Thread(server);
						serverThread.start();
					} 
					catch (Exception e)
					{
						e.printStackTrace();
					}
					
					System.out.println("Server state - " + serverThread.getState());
				}

				Linker.init();
				System.out.println("Server state - " + serverThread.getState());
				
				lastTimeCheck = Utilities.getDateTime("yyyy-MM-dd");
			}
		}
	}
}
